<template>
  <div class="registerBox">
    <el-form :model="registerForm"
             :rules="registerRules"
             ref="registerRef"
             hide-required-asterisk>
      <el-form-item prop="username"
                    style="height:55px">
        <el-input prefix-icon="el-icon-s-opportunity"
                  v-model="registerForm.username"
                  placeholder="账号"></el-input>
      </el-form-item>
      <el-form-item prop="nickname">
        <el-input v-model="registerForm.nickname"
                  placeholder="昵称"
                  prefix-icon="el-icon-coordinate">
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input prefix-icon="el-icon-lock"
                  v-model="registerForm.password"
                  placeholder="密码"
                  show-password></el-input>
      </el-form-item>
      <el-form-item prop="repassword">
        <el-input v-model="registerForm.repassword"
                  placeholder="确认密码"
                  show-password
                  prefix-icon="el-icon-lock"></el-input>
      </el-form-item>
      <el-form-item prop="email">
        <el-input prefix-icon='el-icon-s-comment'
                  v-model='registerForm.email'
                  placeholder="邮箱">
          <el-button slot="append"
                     @click="sendQRCode">{{codeInfo}}</el-button>
        </el-input>
      </el-form-item>
      <el-form-item prop="captcha">
        <el-input v-model="registerForm.captcha"
                  placeholder="验证码"
                  prefix-icon='el-icon-s-promotion'>

        </el-input>
      </el-form-item>
      <el-form-item class="registerButtonWrapper">
        <el-button class="registerButton"
                   type="primary"
                   @click="register">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data () {
    // 自定义邮箱的验证规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z]|[0-9])(\w|-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }

    var checkRePassword = (rule, value, cb) => {
      if (value === this.registerForm.password) return cb()
      cb(new Error('两次密码输入不一致'))
    }
    return {
      // 登录表单数据
      registerForm: {
        username: '',
        password: '',
        nickname: '',
        repassword: '',
        email: '',
        captcha: '',
        // 记录这一次的sessionID，用于后台找到对应的session
        sessionID: ''
      },

      // 记录发送邮件的时间
      time: 0,
      // 发送验证码部分显示的信息
      codeInfo: '发送验证码',

      // 登录规则
      registerRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur'
          }
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          {
            min: 2,
            max: 5,
            message: '长度在 2 到 5 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur'
          }
        ],
        repassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          {
            validator: checkRePassword, trigger: 'blur'
          }
        ],
        email: [
          {
            required: true, message: '请输入邮箱', trigger: 'blur'
          },
          {
            validator: checkEmail, trigger: 'blur'
          }
        ],
        captcha: [
          {
            required: true, message: '请输入验证码', trigger: 'blur'
          }
        ]
      }
    }
  },

  methods: {
    register () {
      this.$refs.registerRef.validate(async (valid) => {
        if (valid) {
          var qs = require('qs')
          this.$http.post('user', qs.stringify(this.registerForm))
            .then((response) => {
              const res = response.data
              if (res.code !== 200) return this.$message.error(res.msg)
              else {
                this.$router.push('/login')
                this.$refs.registerRef.resetFields()
                return this.$message.success(res.msg)
              }
            })
        } else return false
      })
    },
    // 发送验证码
    sendQRCode () {
      // 可以发送
      if (this.registerForm.email === '') {
        return this.$message.error('邮箱输入不得为空')
      }
      if (this.time === 0) {
        // 定时器设置
        this.time = 60
        var intervalID = setInterval(() => {
          this.time--
          this.codeInfo = '等待 (' + this.time + ') s'
          if (this.time === 0) {
            clearInterval(intervalID)
            this.codeInfo = '发送验证码'
          }
        }, 1000)

        this.$http.get('requestQRCode', { params: { email: this.registerForm.email } }).then((response) => {
          const res = response.data
          if (res.code !== 200) return this.$message.error(res.msg)
          this.registerForm.sessionID = res.data
          return this.$message.success(res.msg)
        })
      } else {
        return this.$message.info('等待' + this.time + 's后发送')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.registerBox {
  padding: 50px;
}

.registerButton {
  margin-top: 20px;
  float: right;
}
</style>
